/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Card;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;
import model.Vehicle;
import model.VehicleCategory;

/**
 *
 * @author Aggelos
 */
public class ListProgramForm extends javax.swing.JFrame {

    /**
     * Creates new form ListProgramForm
     */
    public ListProgramForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        query1 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select p from Program p");
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        query2 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        list2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query2.getResultList());
        query3 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select vc from VehicleCategory vc");
        list3 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query3.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButtonNew = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();
        jButtonEdit = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jButtonSave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list1, jTable1, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Περιγραφή");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Πίνακας Προγραμμάτων");
        jLabel1.setToolTipText("");

        jButtonNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        jButtonNew.setText("Νέο");
        jButtonNew.setToolTipText("Δημιουργία νέου προγράμματος");
        jButtonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewActionPerformed(evt);
            }
        });

        jButtonDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        jButtonDelete.setText("Διαγραφή");
        jButtonDelete.setToolTipText("Διαγραφή ενός προγράμματος");
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jButtonEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        jButtonEdit.setText("Επεξεργασία");
        jButtonEdit.setToolTipText("Επεξεργασία στοιχείων προγράμματος");
        jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditActionPerformed(evt);
            }
        });

        jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButtonCancel.setText("Ακυρο");
        jButtonCancel.setToolTipText("Ακύρωση αλλαγών");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jButtonSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jButtonSave.setText("Αποθήκευση");
        jButtonSave.setToolTipText("Αποθήκευση αλλαγών");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonNew)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonEdit)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 836, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButtonCancel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButtonSave))
                                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonNew)
                    .addComponent(jButtonDelete)
                    .addComponent(jButtonEdit))
                .addGap(99, 99, 99)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonCancel))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents
//Λειτουργία πλήκτρου δημιουργίας νέου προγράμματος
    private void jButtonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewActionPerformed
        // TODO add your handling code here:
       p = new Program();
       em.persist(p);
       List<ProgramRate> prl = p.getProgramRateList();
       if (prl==null){
           prl = new ArrayList<ProgramRate>();
           p.setProgramRateList(prl);
       }
       for (Station s: list2){
           for (VehicleCategory vc: list3){
               ProgramRate pr = new ProgramRate();
               pr.setCategoryId(vc);
               pr.setStationId(s);
               pr.setProgramId(p);
               em.persist(pr);
               p.getProgramRateList().add(pr);
           }
       }
     // em.getTransaction().commit();
      
       EditProgramForm epf = new EditProgramForm(p,false);

       epf.setTitle("Δημιουργία νέου προγράμματος");
       epf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        epf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                boolean closeWindow =!arg0.getWindow().isShowing();
                if (closeWindow) {
                     thisFrame.setEnabled(true);
                     em.getTransaction().rollback();
                     em.getTransaction().begin();
                }              
                else if (((MyWindowEvent)arg0).exitAndSave){                                        
                    list1.add(p);
                    int row = list1.size() - 1;
        
                    jTable1.setRowSelectionInterval(row, row);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
       

    }//GEN-LAST:event_jButtonNewActionPerformed
//Λειτουργία πλήκτρου διαγραφής προγράμματος
    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        // TODO add your handling code here:
        int s=jTable1.getSelectedRow();
       //Ελέγχουμε αν έχει επιλεγεί κάποιο πρόγραμμα 
       if ( s < 0 ) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει κάποιο πρόγραμμα για διαγραφή",
                                          "Σφάλμα!",JOptionPane.ERROR_MESSAGE);           
           return;
        }
        Program p = list1.get(jTable1.convertRowIndexToModel(s));       
        if (s>=0) {                        
            //Query queryGetCardId=em.createNativeQuery("SELECT CARD.ID FROM PROGRAM JOIN PROGRAM_RATE "
            //        + "ON (PROGRAM.ID=?programId AND PROGRAM.ID=PROGRAM_RATE.PROGRAM_ID) "
            //        + "JOIN VEHICLE_CATEGORY ON VEHICLE_CATEGORY.ID=PROGRAM_RATE.CATEGORY_ID "
            //        + "JOIN VEHICLE ON VEHICLE_CATEGORY.ID=VEHICLE.CATEGORY_ID JOIN CARD ON CARD.ID=VEHICLE.CARD_ID")
            //            .setParameter("programId", p.getId());            
           // List cards=queryGetCardId.getResultList();
            //Ελέγχουμε αν υπάρχουν οχήματα που ανήκουν στο πρόγραμμα
           // if(cards.size()>0) {
           //     String warning="Το πρόγραμματα δε μπορεί να διαγραφεί γιατί υπάρχουν οχήματα που ανήκουν σ' αυτό";
           //     JOptionPane.showMessageDialog(this,warning,"Σφάλμα",JOptionPane.ERROR_MESSAGE);
           // } else{
                Query queryProgramRate = em.createQuery("select pr from ProgramRate pr where pr.programId=:programId")
                        .setParameter("programId", p);
                List<ProgramRate> lpr = queryProgramRate.getResultList();
                //Διαγραφή οχημάτων
                for (ProgramRate pr: lpr) {
                    em.remove(pr);
                }
                list1.remove(p);
                em.remove(p);   
            //}
        }         
    }//GEN-LAST:event_jButtonDeleteActionPerformed
//Λειτουργία πλήκτρου επεξεργασίας προγράμματος
    private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
        // TODO add your handling code here:
       s= jTable1.getSelectedRow();
       //Ελέγχουμε αν έχει επιλεγεί κάποιο πρόγραμμα 
       if ( s < 0 ) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει κάποιο πρόγραμμα ",
                                          "Σφάλμα!",JOptionPane.ERROR_MESSAGE);           
           return;
        }       
       p = list1.get(s);
       EditProgramForm ecf = new EditProgramForm(p,false,true);
       ecf.setTitle("Επεξεργασία προγράμματος");
       ecf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        ecf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                boolean closeWindow =!arg0.getWindow().isShowing();
                if (closeWindow) {
                     thisFrame.setEnabled(true);
                     em.getTransaction().rollback();
                     em.getTransaction().begin();
                }              
                else if (((MyWindowEvent)arg0).exitAndSave){
//Οριστικοποίηση αλλαγών                    
                    em.persist(p);
                    em.getTransaction().commit();
                    em.getTransaction().begin();                       
//                    
                    list1.set(s,p);
                    jTable1.setRowSelectionInterval(s, s);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_jButtonEditActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        // TODO add your handling code here:
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        // TODO add your handling code here:
        //  this.avenuePUEntityManager.persist(this.vehicle1);
        em.getTransaction().commit();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_jButtonSaveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListProgramForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JButton jButtonEdit;
    private javax.swing.JButton jButtonNew;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private java.util.List<Program> list1;
    private java.util.List<Station> list2;
    private java.util.List<VehicleCategory> list3;
    private javax.persistence.Query query1;
    private javax.persistence.Query query2;
    private javax.persistence.Query query3;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    JFrame thisFrame;
    Program p;
    int s ;
}
